<template>
  <div class="rmsDetail">
    <div class="search">
      <div class="tableScreen">
        <el-form ref="form"
                 label-width="100px">
          <el-form-item label="合同编号">
            <el-input v-model="params.contractNo"
                      style="width: 226px"
                      placeholder="请输入合同编号"></el-input>
          </el-form-item>
          <el-form-item v-if="menuId == 322"
                        label="承运方名称">
            <el-input v-model="params.carrierName"
                      style="width: 226px"
                      placeholder="请输入承运方名称"></el-input>
          </el-form-item>
          <el-form-item v-if="menuId != 322 && menuId != 367 && menuId != 368 &&
                              menuId != 318 && menuId != 332"
                        label="收货方名称">
            <el-input v-model="params.consigneeName"
                      style="width: 226px"
                      placeholder="请输入收货方名称"></el-input>
          </el-form-item>
          <el-form-item v-if="menuId == 335"
                        label="已关闭">
            <el-select v-model="params.isClose"
                       placeholder="请选择"
                       style="width: 226px"
                       clearable>
              <el-option v-for="(item,index) in isCloseList"
                         :key="index"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="buttonSearch_left">
        <el-button type="primary"
                   :loading="loading"
                   class="newConfirmButton"
                   @click="sureBill">搜索</el-button>
        <el-button type="primary"
                   :loading="loading"
                   class="newCancelButton"
                   @click="reset">重置</el-button>
      </div>
    </div>
    <el-form>
      <el-form-item style="float: right">
        <el-button type="default"
                   icon="el-icon-s-promotion"
                   @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading"
              class="table-borders"
              :class="tableData.length < 10 ? 'table-border' : ''"
              height="540"
              :data="tableData"
              size="mini"
              border
              element-loading-text="加载中"
              element-loading-spinner="el-icon-loading"
              tooltip-effect="dark"
              highlight-current-row
              :show-summary="showSummary(menuId)"
              :summary-method="getSummaries"
              @sort-change="sortChange">
      <el-table-column v-for="(column, index) in columns"
                       :key="index"
                       :prop="column.prop"
                       :label="column.name"
                       :width="column.width"
                       :align="column.align?column.align:'right'"
                       :sortable="column.sortable?'custom':false">
        <template slot-scope="scope">
          <span v-if="column.prop == 'contractNo' &&
                (menuId == 335)">
            <span :show-overflow-tooltip="true"
                  :style="scope.row.isClose?'width: 100px;':'width: 128px;'"
                  style="display: inline-block;">{{scope.row[column.prop]}}</span>
            <section v-if="scope.row.isClose"
                     class="section-wrap closePrompt">
              <el-tooltip class="item"
                          effect="dark"
                          content="发货方运单已关闭"
                          placement="top-start">
                <span><i class="el-icon-warning-outline closePrompt"></i></span>
              </el-tooltip>
            </section>
          </span>
          <span v-else-if="column.align != 'left' && column.align != 'center'">{{conversion(scope.row[column.prop])}}</span>
          <span v-else="">{{scope.row[column.prop]}}</span>
        </template>
      </el-table-column>
    </el-table>
    <span v-show="tableData.length > 0 && menuId != 367 && menuId != 368 && 
          menuId != 318 && menuId != 332"
          style="color: var(--prev-color-primary);">说明:由于四舍五入的原因，本页合计和总合计可能存在误差。</span>
    <el-pagination background
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total"
                   :page-sizes="pageSizeOptions"
                   :page-size.sync="params.size"
                   :current-page.sync="params.page"
                   @size-change="loadData"
                   @current-change="loadData">
    </el-pagination>
  </div>
</template>

<script>
import rmsApi from '@/api/modules/rms'
import { mapActions } from "vuex";
import { table } from "@/api";
import { columnsScreen, derives, evaluateScreen, evaluate } from "@/libs/rmsColumns.js";
export default {
  name: "RmsDetail",
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    shipTime: {
      type: Object,
      default: () => { }
    },
    shipType: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      tableData: [],
      columns: [],
      total: 0,
      menuId: 0,
      time: '',
      loading: false,
      pageSizeOptions: [10, 20, 50, 100, 500],
      isCloseList: [{
        label: '是',
        value: true
      }, {
        label: '否',
        value: false
      }],
      params: {
        contractNo: "",
        customerName: "",
        carrierName: "",
        queryStartTime: "",
        queryEndTime: "",
        type: 1,
        page: 1,
        size: 10,
      },
      allTotal: {},
      currentTotal: {},
      derive: {}
    };
  },
  created () {
    this.derive = derives(this.menuId);
  },
  methods: {
    locationInHone () {
      this.menuId = this.$store.state.menu.menu.menuId
      this.params.queryStartTime = this.shipTime.queryStartTime
      this.params.queryEndTime = this.shipTime.queryEndTime
      if (this.value.id) {
        this.params.relationId = this.value.id.relationId
      } else {
        delete this.params.relationId
      }
      if (this.menuId == 323) {
        this.params.shipMode = this.value.expenseName == '市内' ? 1 : 2
      } else if (this.menuId == 324) {
        this.params.transportMode = this.value.expenseName == '零担' ? 1 : 2
      } else if (this.menuId == 311 || this.menuId == 335) {
        if (this.value.id.ccId) {
          this.params.customerId = this.value.id.ccId
        } else {
          delete this.params.customerId
        }
      } else if (this.menuId == 321) {
        if (this.value.id.ccId) {
          this.params.carrierId = this.value.id.ccId
        } else {
          delete this.params.carrierId
        }
      } else if (this.menuId == 322) {
        this.params.consigneeId = this.value.id.consigneeId ? this.value.id.consigneeId : ''
      } else if (this.menuId == 367) {
        this.params.carrierId = this.value.carrierId ? this.value.carrierId : ''
      } else if (this.menuId == 368) {
        this.params.customerId = this.value.customerId ? this.value.customerId : ''
      }
      if (this.menuId == 332) {
        // this.params.carrierId = this.value.ccId ? this.value.ccId : 0
        if (this.value.ccId) {
          this.params.carrierId = this.value.ccId
        } else {
          delete this.params.carrierId
        }
        delete this.params.customerId
      } else if (this.menuId == 318) {
        // this.params.customerId = this.value.ccId ? this.value.ccId : 0
        if (this.value.ccId) {
          this.params.customerId = this.value.ccId
        } else {
          delete this.params.customerId
        }
        delete this.params.carrierId
      }
      if (this.menuId == 318 || this.menuId == 332) {
        this.params = Object.assign( {}, this.params, this.value )
        delete this.params.month
        this.columns = evaluateScreen(this.shipType);
        this.derive = evaluate(this.shipType);
      } else {
        this.columns = columnsScreen(this.menuId);
        this.derive = derives(this.menuId);
      }
      this.loadData();
    },
    initialData (value) {
      let now = new Date();
      let currentYear = now.getFullYear()
      let currentMonth = now.getMonth() + 1;
      let currentTime = String(currentYear) + (currentMonth < 10 ? '0' +
        String(currentMonth) : String(currentMonth));
      return value = currentTime
    },
    showSummary (menuId) {
      let Booleans
      if (menuId == 367 || menuId == 368 || menuId == 318 || menuId == 332) {
        Booleans = false
      } else {
        Booleans = true
      }
      return Booleans
    },
    async loadData () {
      this.loading = true
      let synthesis
      if (this.menuId == 318 || this.menuId == 332) synthesis = true
      let { data } = synthesis?await rmsApi.search(this.params, this.shipType):await rmsApi.search(this.params, this.menuId);
      let code = data.code
      let datas = data.data
      if (code === 0) {
        this.loading = false
        this.tableData = datas.records;
        this.allTotal = datas.allTotal
        this.currentTotal = datas.currentTotal
        this.total = datas.total;
      } else {
        this.loading = false
      }
    },
    // 导出
    async handleExport () {
      if (!this.tableData.length) {
        this.$message.warning("没有可要导出的数据！");
        return false;
      }
      let args = JSON.parse(JSON.stringify(this.params))
      args.page = 1
      args.size = this.total
      let params = {
        args: { ...args },
        name: this.derive.name,
        type: this.derive.type
      };
      await table.submitFormContainer(`/export/task`, params);
      this.searchCount()
      this.$nextTick(() => {
        this.$message.success("导出功能正在后台执行中，请稍后去“导出文件”下载中查看！");
      });
    },
    // 查询导出未读数
    ...mapActions({
      searchCount: "login/exportCount"
    }),
    //排序
    sortChange (val) {
      let name = val.prop
      this.params.sort = []
      this.params.sort = [{
        asc: false,
        name: ''
      }]
      if (val.order == 'descending') {
        this.params.sort[0].asc = false
        this.params.sort[0].name = val.prop
      } else if (val.order == 'ascending') {
        this.params.sort[0].asc = true
        this.params.sort[0].name = val.prop
      } else {
        delete this.params.sort
      }
      this.sureBill();
    },
    sureBill () {
      this.currentPage = 1;
      this.params.page = 1;
      this.loading = true;
      this.loadData();
    },
    reset () {
      this.params.contractNo = "";
      this.params.contractNo = "";
      this.params.consigneeName = "";
      this.params.carrierName = "";
      this.params.isClose = null
      delete this.params.sort
      this.params.queryStartTime = this.shipTime.queryStartTime,
        this.params.queryEndTime = this.shipTime.queryEndTime,
        this.sureBill();
    },
    //科学计数法
    conversion (val) {
      return JSON.stringify(val ? val : 0).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        let el
        if (index === 0) {
          el = <p>本页合计：<br /><br />总合计：</p> // 主要代码
          sums[index] = el
          return;
        }
        if (column.label == '收入（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountIncome) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountIncome) }}</p>
        } else if (column.label == '运单数（单）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalWaybill) }}<br /><br />{{ text: this.conversion(this.allTotal.totalWaybill) }}</p>
        } else if (column.label == '成本（元）' || column.label == '总成本（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountCost) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountCost) }}</p>
        } else if (column.label == '利润（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.profits) }}<br /><br />{{ text: this.conversion(this.allTotal.profits) }}</p>
        } else if (column.label == '零担费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeDivide) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeDivide) }}</p>
        } else if (column.label == '整车费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeWhole) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeWhole) }}</p>
        } else if (column.label == '提货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeePick) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeePick) }}</p>
        } else if (column.label == '送货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeDeliver) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeDeliver) }}</p>
        } else if (column.label == '装货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeLoad) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeLoad) }}</p>
        } else if (column.label == '卸货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeUnload) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeUnload) }}</p>
        } else if (column.label == '补充费用（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeSupplement) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeSupplement) }}</p>
        } else if (column.label == '最低运费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeMin) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeMin) }}</p>
        } else if (column.label == '保险费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeInsure) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeInsure) }}</p>
        } else if (column.label == '税费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeTax) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeTax) }}</p>
        } else if (column.label == '总重量（公斤）' || column.label == '重量（公斤）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalWeight) }}<br /><br />{{ text: this.conversion(this.allTotal.totalWeight) }}</p>
        } else if (column.label == '总体积（方）' || column.label == '体积（方）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalVolume) }}<br /><br />{{ text: this.conversion(this.allTotal.totalVolume) }}</p>
        }
        sums[index] = el
        return;
      });
      return sums;
    },
  },
  watch: {
    value: {
      immediate: true,
      handler (val) {
        if (this.value) {
          setTimeout(() => {
            this.currentPage = 1;
            this.tableData = []
            this.params = {
              contractNo: "",
              customerName: "",
              carrierName: "",
              queryStartTime: "",
              queryEndTime: "",
              type: 1,
              page: 1,
              size: 10,
            }
            this.locationInHone();
          }, 100)
        }
      }
    },
  }
};
</script>
<style scoped>
.rmsDetail >>> .search {
  overflow: hidden;
  padding: 10px 0;
}
.rmsDetail >>> .tableScreen {
  width: 80%;
  float: left;
  margin-right: 10px;
}
.tableScreen >>> .el-form {
  display: flex;
}
.rmsDetail >>> .buttonSearch_left {
  width: 202px;
  float: right;
}
.rmsDetail >>> .el-table th.el-table__cell .cell {
  height: 40px !important;
}
.table-borders >>> .el-table__body-wrapper {
  height: calc(100% - 168px) !important;
  overflow-y: auto;
}
.rmsDetail .closePrompt {
  font-size: 20px;
  color: var(--prev-color-primary);
  line-height: inherit;
  float: right;
}
</style>
